package itsm.isperp.framework.data.jdbc;

import itsm.isperp.framework.domain.IBean;
import itsm.isperp.framework.utils.ReflectHelper;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-12-1
 * @since 1.0
 * 
 */
public class BeanRowMapper<T extends IBean> implements RowMapper<T> {

	Class<T> clazz;

	public BeanRowMapper(Class<T> clazz) {
		this.clazz = clazz;
	}

	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		T t = null;
		try {
			t = clazz.newInstance();
		} catch (Exception e) {
			return null;
		}

		ResultSetMetaData rsmd = rs.getMetaData();
		int columnCount = rsmd.getColumnCount();

		for (int i = 1; i <= columnCount; i++) {
			String field = itsm.isperp.framework.utils.StringUtils
					.camelCaseWord(JdbcUtils.lookupColumnName(rsmd, i)
							.toLowerCase());
			Object v = getColumnValue(rs, i);
			try {
				ReflectHelper.setValueByFieldName(t, field, v);
			} catch (Exception e) {

				if (v instanceof Number) {
					Number m = (Number) v;
					m.intValue();

					try {
						ReflectHelper.setValueByFieldName(t, field, v);
					} catch (Exception e1) {

					}

				}

			}
		}

		return t;
	}

	protected Object getColumnValue(ResultSet rs, int index)
			throws SQLException {
		return JdbcUtils.getResultSetValue(rs, index);
	}
}
